<template>
  <div class="card" style="padding: 40px 20px; width: 40%">
    <el-form ref="formRef" :rules="data.rules" :model="data.form" style="padding-right: 50px; padding-top:20px">
      <el-form-item label="原密码" :label-width="80" prop="password">
        <el-input v-model="data.form.password" autocomplete="off" show-password placeholder="请输入原密码"/>
      </el-form-item>
      <el-form-item label="新密码" :label-width="80" prop="newPassword">
        <el-input v-model="data.form.newPassword" autocomplete="off" show-password placeholder="请输入新密码"/>
      </el-form-item>
      <el-form-item label="确认密码" :label-width="80" prop="confirmPassword" required>
        <el-input v-model="data.form.confirmPassword" autocomplete="off" show-password placeholder="请确认新密码"/>
      </el-form-item>
      <div style="text-align: center;">
        <el-button type="primary" @click="updatePassword" style="padding: 20px 30px">立即修改</el-button>
      </div>
     </el-form>
  </div>
</template>


<script setup>
import {reactive, ref} from "vue";
import {ElMessage} from "element-plus";
import request from "@/utils/request.js";

const formRef = ref()

const validatePass = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请确认密码'))
  }  else if (value !== data.form.newPassword) {
    callback(new Error("密码不一致"))
  }else if(value === data.form.password){
    callback(new Error("新密码不能与原密码相同"))
  }
  else {
    callback()
  }
}

const data = reactive({
  user: JSON.parse(localStorage.getItem('xm-pro-user')),
  form: {},
  rules: {
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' }
    ],
    newPassword: [
      { required: true, message: '请输入新密码', trigger: 'blur' }
    ],
    confirmPassword: [{
      validator: validatePass, trigger: 'blur'
    }]
  }
})

const updatePassword = () => {
  data.form.id = data.user.id
  data.form.role = data.user.role
  formRef.value.validate(valid =>{
    if (valid) {
      request.put('/updatePassword', data.form).then(res =>{
        if(res.code === '200'){
          ElMessage.success('修改成功')
          localStorage.removeItem('xm-pro-user')
          setTimeout(() => {
            location.href = '/login'
          }, 500)
        }else{
          ElMessage.error(res.msg)
        }
      })
    }
  })
}



</script>


<style>

</style>

